<template>
	<view class="order-place">
		<view class="head-tools">
			<button class="btn " :class="{ 'btn-gray': pickupWay != 'visit', 'btn-yellow': pickupWay == 'visit' }" @click="pickupWay = 'visit'">配送上门</button>
			<button class="btn " :class="{ 'btn-gray': pickupWay != 'pickup', 'btn-yellow': pickupWay == 'pickup' }" @click="pickupWay = 'pickup'">集中收货自提</button>
		</view>
		<view class="order-content">
			<navigator class="address-select" v-if="pickupWay == 'visit'" :url="'/pages/address/address?title=选择收货地址&type=select'" hover-class="none">
				<!-- 收货地址选择 -->
				<image class="icon" src="/static/loc-s.png" mode=""></image>
				<view class="address-content" v-if="takeAddress.takeName">
					<view class="user">
						<text class="user-name">{{ takeAddress.takeName }}</text>
						<text class="user-phone">{{ takeAddress.iphone }}</text>
					</view>
					<text class="address-text">{{ takeAddress.city }}-{{ takeAddress.county }} {{ takeAddress.address }}</text>
				</view>
				<view class="address-content" v-else>请选择收货地址</view>
			</navigator>
			<navigator class="address-select" v-if="pickupWay == 'pickup'" :url="'/pages/address/receive-point'" hover-class="none">
				<!-- 集中收货地址选择 -->
				<image class="icon" src="/static/loc-s.png" mode=""></image>
				<view class="address-content" v-if="focusTakeAddress.takeName">
					<view class="user">
						<text class="user-name">{{ focusTakeAddress.takeName }}</text>
						<text class="user-phone">{{ focusTakeAddress.iphone }}</text>
					</view>
					<text class="address-text">{{ focusTakeAddress.city }}-{{ focusTakeAddress.county }} {{ focusTakeAddress.address }}</text>
				</view>
				<view class="address-content" v-else>请选择集中收货地址</view>
			</navigator>
			<view class="good-close-card">
				<!-- 商品结算卡片 -->
				<view class="goods-list">
					<navigator
						class="good-item"
						:url="'/pages/goods/goods?name=' + item.commodityName + '&id=' + item.commodityId"
						hover-class="none"
						:key="item.commodityId"
						v-for="(item, index) in goodList"
					>
						<goods-item
							type="cross"
							:name-size="36"
							:name-row-num="2"
							:good-num="item.buyCount"
							:img="imgHost + item.commodityPic"
							:img-width="'150rpx'"
							:img-height="'200rpx'"
							:price="item.sellPrice"
							:name="item.commodityName"
						></goods-item>
					</navigator>
				</view>
				<view class="info-list">
					<uniForms class="form">
						<formListItem
							class="item"
							:label-width="150"
							:label="'买家备注'"
							placeholder="未填写"
							:input-text-align="'right'"
							:maxlength="500"
							:value.sync="messageInfo"
						></formListItem>
						<!-- <formListItem
								class="item"
								:label-width="150"
								:read-only="true"
								:label="'优惠券'"
								placeholder="未填写"
								:input-text-align="'right'"
								:value="phone"
							></formListItem> -->
						<formListItem
							class="item"
							:label-width="150"
							:read-only="true"
							:label="'商品总额'"
							placeholder="未填写"
							:input-text-align="'right'"
							:value="goodsPrice"
						></formListItem>
						<formListItem
							class="item"
							:read-only="true"
							:label-width="150"
							:label="'配送费'"
							placeholder="未填写"
							:input-text-align="'right'"
							:value="orderFreight"
						></formListItem>
						<formListItem
							class="item"
							type="route"
							:route-link="'/pages/order/invoice-edit'"
							:read-only="true"
							:arrow-show="true"
							:label-width="150"
							:label="'发票信息'"
							placeholder="未填写"
							:input-text-align="'right'"
							:value="invoice"
							:maxlength="500"
						></formListItem>
					</uniForms>
				</view>
				<view class="total">
					<view class="numerical">
						<text class="total-num">共{{ goodNum }}件</text>
						<view class="sumpay">
							<text class="label">小计</text>
							<text class="symbol">¥</text>
							<text class="num">{{ goodsPrice }}</text>
						</view>
					</view>
				</view>
			</view>
			<view class="pay-way">
				<view class="title">支付方式</view>
				<list-item
					class="item"
					v-for="(item, index) in payWayList"
					:key="index"
					:icon-nol="item.icon"
					:name="item.title"
					:name-size="34"
					:icon-size="50"
					:name-color="'#46494D'"
					:arrow-show="false"
				></list-item>
				<!-- <view class="item">微信支付</view> -->
			</view>
		</view>
		<view class="tools-foots">
			<view class="total-money">
				<text class="money">¥{{ orderPrice }}</text>
			</view>
			<button class="btn btn-orange close" @click="goToPlaceOrder">结算订单</button>
		</view>
	</view>
</template>

<script>
import goodsItem from '@/components/goods-item/goods-item.vue';
import uniForms from '@/components/uni-forms/uni-forms.vue';
import formListItem from '@/components/form-list-item/form-list-item.vue';
import listItem from '@/components/list-item/list-item.vue';
export default {
	components: {
		goodsItem,
		uniForms,
		formListItem,
		listItem
	},
	data() {
		return {
			imgHost: this.$imgHost,
			orderNo: '', //订单号
			pickupWay: 'visit', //取货方式 visit：配送上门 ,pickup：集中取货自提
			type: 'catr', //下单类型 购物车:'catr' 商品:'good' 继续'continue'
			goodId: '', //商品id
			takeAddress: this.$store.state.orderModule.takeAddress, //收货地址
			focusTakeAddress: this.$store.state.orderModule.focusTakeAddress, //集中收货地址
			orderFreightDefaultVal: 0, //订单运费默认值
			// {
			// 收货人地址
			// addresAlias: null
			// addresType: 0
			// address: "榄树排东街12巷3号"
			// city: "广州市"
			// county: "黄埔区"
			// createBy: ""
			// createTime: "2021-01-11 03:40:27"
			// fixIphone: null
			// id: 20
			// iphone: "18202074132"
			// isDefault: 1
			// params: Object
			// province: "广东省"
			// remark: null
			// searchValue: null
			// takeName: "饶东俊"
			// updateBy: ""
			// updateTime: "2021-01-11 03:40:59"
			// userId: 3
			// },
			goodList: this.$store.state.orderModule.editOrderFrom.goodsList,
			// [
			// 	{
			// author: "十万个为什么 上册"
			// buyCount
			// goodsPrice:1
			// categoryId: 19
			// commodityCode: "100100100"
			// commodityId: 8
			// commodityName: "十万个为什么 上册"
			// commodityPic: "/profile/upload/afb37c4f-68ae-4411-9c47-b47a5353aa4d.jpg"
			// commodityRotationPic: "/profile/upload/eb0964ac-bb95-4439-8555-be233b96e3d6.jpg,/profile/upload/8600a944-2745-484f-82e8-5f99d2f98c62.jpg"
			// createBy: ""
			// createTime: "2021-01-08 07:23:40"
			// freeMailStatus: 0
			// marketPrice: 100
			// orderNum: 0
			// params: {}
			// postage: null
			// press: "十万个为什么 上册"
			// pressDate: "2021-01-12"
			// remark: ""
			// searchValue: null
			// sellPrice: 100
			// status: 1
			// stock: 100
			// updateBy: ""
			// updateTime: null
			// 	}
			// ],
			payWayList: [
				//支付方式列表
				{
					icon: '/static/weixin.png',
					title: '微信支付'
					// path: '/pages/mine/mine-edit'
				}
			],
			postageTemplate: {
				// 运费模板信息
			},
			messageInfo: '', //备注
			invoice: null
		};
	},
	computed: {
		loginInfo() {
			// 登录信息
			return this.$store.state.loginModule;
		},
		userInfo() {
			// 用户信息
			return this.$store.state.userModule.userInfo;
		},
		goodNum() {
			// 购物车商品数量

			let result = 0;
			this.goodList.forEach(item => {
				result = result + item.buyCount;
			});

			return result;
		},
		goodsPrice() {
			//商品总额
			let result = 0;
			this.goodList.forEach(item => {
				result = parseFloat(new this.$BigNumber(result).plus(new this.$BigNumber(item.sellPrice).multipliedBy(item.buyCount)));
			});
			return result;
		},
		orderFreight() {
			//订单运费
			let result = 0;
			if (this.type != 'continue') {
				if (this.goodsPrice < this.postageTemplate.meetAmount) {
					for (var i = 0; i < this.goodList.length; i++) {
						let item = this.goodList[i];
						if (item.freeMailStatus == 1 || item.postage == null) {
							result = '免费';
							break;
						} else if (item.postage > result) result = item.postage;
					}

					return result ? result : '免费';
				} else return '免费';
			} else {
				return this.orderFreightDefaultVal ? this.orderFreightDefaultVal : '免费';
			}
		},
		orderPrice() {
			let orderFreight;
			if (this.orderFreight == '免费') orderFreight = 0;
			else orderFreight = this.orderFreight;
			return parseFloat(new this.$BigNumber(this.goodsPrice).plus(orderFreight));
		},
		invoiceInfo() {
			// 发票信息
			console.log('发票信息');
			return this.$store.state.orderModule.invoiceData;
			// {
			// orderNo:"", //订单号
			// invoiceType:0, //发票类型
			// invoiceTitle:"", //发票抬头
			// invoiceTaxNo:"", //发票税号
			// invoiceEmail:"", //开票邮箱
			// invoiceTax:"", //开票税金
			// vatCompanyAddress:"" ,//公司地址
			// vatTelphone:"" ,//联系电话
			// vatBankName:"" ,//开户银行
			// vatBankAccount:"" ,//银行账号
			// } //发票信息
		}
	},
	watch: {
		'$store.state.orderModule.editOrderFrom': function(nelVal, oldVal) {
			console.log('编辑订单表更新', nelVal);
		},
		'$store.state.orderModule.takeAddress': function(nelVal, oldVal) {
			console.log('收货人地址更新', nelVal, oldVal);
			this.takeAddress = nelVal;
		},
		'$store.state.orderModule.focusTakeAddress': function(nelVal, oldVal) {
			console.log('集中收货地址选择更新', nelVal, oldVal);
			this.focusTakeAddress = nelVal;
		},
		'$store.state.orderModule.invoiceData': function(newVal, oldVal) {
			console.log('发票变化', newVal);
			if (newVal && newVal.invoiceTitle && newVal.invoiceTitle != '' && newVal.invoiceEmail && newVal.invoiceEmail != '') {
				if (newVal.invoiceType == 0) this.invoice = '个人发票';
				else if (newVal.invoiceType == 1) this.invoice = '单位发票';
			} else {
				this.invoice = null;
			}
		}
	},
	methods: {
		verification() {
			// 验证
			console.log('验证', this.pickupWay == 'visit' && this.takeAddress && this.takeAddress.takeName);
			if (this.pickupWay == 'visit' && this.takeAddress && !this.takeAddress.takeName) {
				uni.showToast({
					icon: 'none',
					mask: true,
					duration: 2000,
					title: '请选择地址！'
				});
				return false;
			} else if (this.pickupWay == 'pickup' && this.focusTakeAddress && !this.focusTakeAddress.takeName) {
				uni.showToast({
					icon: 'none',
					mask: true,
					duration: 2000,
					title: '请选择集中收货地址！'
				});
				return false;
			} else {
				return true;
			}
		},
		getPostageTemplate() {
			// 获取支付模板信息
			this.$store.dispatch('getPostageTemplate').then(res => {
				console.log('查询运费模板', res);
				let data = res.data.data;
				this.postageTemplate = data;
			});
		},
		goToPlaceOrder() {
			// 结算订单
			if (this.loginInfo.token && this.loginInfo.token != '') {
				// 已登录
				if (this.userInfo && this.userInfo.school && this.userInfo.banji && this.userInfo.school != '' && this.userInfo.banji != '') {
					if (this.verification()) {
						// 验证通过
						if (this.type != 'continue') {
							let addressInfo;
							if (this.pickupWay == 'visit') addressInfo = this.takeAddress;
							else addressInfo = this.focusTakeAddress;
							let option = {
								orderPrice: this.orderPrice,
								goodsPrice: this.goodsPrice,
								orderFreight: this.orderFreight && this.orderFreight == '免费' ? 0 : this.orderFreight,
								takeName: addressInfo.takeName,
								iphone: addressInfo.iphone,
								province: addressInfo.province,
								city: addressInfo.city,
								county: addressInfo.county,
								address: addressInfo.address,
								messageInfo: this.messageInfo,
								goodsList: this.goodList.map(item => {
									return {
										goodsId: item.commodityId || item.goodsId,
										goodsName: item.commodityName,
										goodsPic: item.commodityPic,
										goodsPrise: item.sellPrice,
										buyCount: item.buyCount
									};
								}),
								billType: this.invoice ? 1 : 0,
								jpOrdersInvoice: this.invoiceInfo
							};
							this.$store.dispatch('addOrder', option).then(res => {
								
								let data = res.data.data;
								if (this.type == 'catr') this.$store.dispatch('clearCheckGoodAction');
								// #ifdef MP
								this.pay(data);
								// #endif
							}).catch(err=>{
								console.log('添加订单错误', err);
								if(err&&err.data&&this.type == 'catr'&&err.data.code==500)
								uni.switchTab({
									url:"/pages/main/catr"
								})
							});
						} else {
							this.$store
								.dispatch('payAgain', {
									orderNo: this.orderNo
								})
								.then(res => {
									console.log('再次下单', res);
									let data = res.data.data;
									// #ifdef MP
									this.pay(data);
									// #endif
								});
						}
					}
				} else {
					uni.showToast({
						icon: 'none',
						mask: true,
						title: '初次下单需要填写学校班级信息！',
						duration: 2000
					});
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/mine/mine-edit?type=replenish'
						});
					}, 2000);
				}
				// uni.navigateTo({
				// 	url: '/pages/order/pay-result?type=success'
				// });
			} else {
				uni.showToast({
					icon: 'none',
					mask: true,
					title: '请登录后下单！',
					duration: 2000
				});
				setTimeout(() => {
					uni.switchTab({
						url: '/pages/main/mine'
					});
				}, 2000);
			}
		},
		pay(params) {
			uni.requestPayment({
				// #ifdef MP-ALIPAY
				provider: 'alipay',
				orderInfo: {},
				// #endif
				// #ifdef MP-WEIXIN
				provider: 'wxpay',
				timeStamp: params.timeStamp,
				nonceStr: params.nonceStr,
				package: params.packageValue,
				signType: params.signType,
				paySign: params.paySign,
				// #endif
				success: res => {
					console.log('success:', res);
					uni.redirectTo({
						url: '/pages/order/pay-result?type=success'
					});
				},
				fail: err => {
					console.log('fail:', err);
					uni.showToast({
						mask: true,
						duration: 2000,
						title: '支付失败！'
					});
				}
			});
		}
	},
	onLoad(option) {
		if (option.type) this.type = option.type;
		if (option.orderNo) this.orderNo = option.orderNo;
		if (option.goodId) this.goodId = option.goodId;
		if (option.orderFreight) this.orderFreightDefaultVal = parseInt(option.orderFreight);

		this.getPostageTemplate();
	}
};
</script>

<style lang="scss" scoped>
.order-place {
	margin-bottom: 100rpx;
	.head-tools {
		background-color: #fff;
		padding: 20rpx 20rpx;
		margin-bottom: 20rpx;
		display: flex;
		justify-content: space-between;
		.btn {
			width: 340rpx;
			padding: 16rpx 0rpx;
		}
	}
	.order-steps {
		// padding-bottom: 20rpx;

		margin-top: 50rpx;
	}
	.order-content {
		padding: 0rpx 20rpx 20rpx 20rpx;
	}
	.pay-way {
		// border-bottom: 2rpx solid #efeff0;
		background-color: #fff;
		margin-top: 20rpx;
		border-radius: 6px;
		.title {
			color: #46494d;
			font-weight: bolder;
			font-size: 34rpx;
			padding: 20rpx 36rpx;
		}

		.item {
			// color: #46494d;
			// font-size: 34rpx;
			/* #ifdef H5 */
			padding: 20rpx 36rpx !important;
			/* #endif */

			/* #ifdef MP */
			::v-deep .list-item {
				padding: 20rpx 36rpx !important;
			}
			/* #endif */
		}
	}
	.tools-foots {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 100%;
		background-color: #fff;
		position: fixed;
		bottom: 0;
		box-sizing: border-box;
		padding: 14rpx 24rpx 14rpx 36rpx;
		box-shadow: 0px 0px 8rpx #333;
		.total-money {
			margin-right: 20rpx;
			font-size: 32rpx;
			.money {
				color: #ff6106;
				margin-left: 10rpx;
				font-size: 32rpx;
			}
		}
		.close {
			padding: 15rpx 80rpx;
			font-size: 32rpx;
		}
	}
}
</style>
